package com.lagou.service.impl;

import com.lagou.entity.Position;
import com.lagou.service.PositionService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class PositionServiceImpl implements PositionService {
    private  static final Logger logger= LogManager.
            getLogger(PositionServiceImpl.class);

    private RestHighLevelClient client;
    private static final String POSITION_INDEX="position";

    @Override
    public List<Map<String,Object>> queryPositions(String query) throws IOException {
        SearchRequest searchRequest= new SearchRequest(POSITION_INDEX);
       SearchSourceBuilder searchSourceBuilder= new SearchSourceBuilder();
        MatchQueryBuilder positionName = QueryBuilders.matchQuery("positionName", query);
        searchSourceBuilder.query(positionName);
        searchSourceBuilder.timeout(new TimeValue(30, TimeUnit.SECONDS));
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        ArrayList<Map<String,Object>> list= new ArrayList<>();
        SearchHit[] hits = search.getHits().getHits();
        for (SearchHit hit: hits) {
            list.add(hit.getSourceAsMap());
        }
        return list;
    }
}
